package com.war.service.safeManage;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.war.dao.safeManage.UserDao;
import com.war.pojo.system.User;
import com.war.util.MdFive;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    MdFive mdFive;
    //获取发件人邮箱
    @Value("${spring.mail.username}")
    String sendEmail;
    //创建发送邮件的的对象
    @Autowired
    JavaMailSender mailSender;

    @Override
    public String checkIdentity(HttpServletRequest request) {
        //返回session中用户信息的身份
        HttpSession session = request.getSession();
        User u = (User) session.getAttribute("user");
        return u.getIdentity();
    }

    @Override
    public Boolean checkLogin(HttpServletRequest request) {
        //检查session中是否有用户信息，返回检查结果
        HttpSession session = request.getSession();
        User u = (User) session.getAttribute("user");
        if (u == null){
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    @Override
    public String login(User user, HttpServletRequest request) {
        //查询盐值
        String salt = userDao.valSalt(user);
        //将用户输入的密码进行加密，并存到数据层
        String pwd = mdFive.encrypt(user.getLogin_pwd(), salt);
        user.setLogin_pwd(pwd);
        System.out.println("AAAAAAAAAAAAAA:"+pwd);
        //调用数据层的登录方法，并且拿到返回值
        User user2 = userDao.login(user);
        if(user2 != null){
            //将用户对象存入session
            HttpSession session = request.getSession();
            session.setAttribute("user", user2);
            return "登录成功";
        }
        return "登录失败";
    }

    @Override
    public HashMap<String, Object> sendCode(String email, HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        User user = new User();
        user.setEmail(email);
        user = (userDao.valEmail(user)).get(0); //本来应该只能select出一个，但没有做邮箱注册限制，故暂时用列表第一个登录
        if (user == null){
            map.put("info","用户不存在，或用户未添加邮箱信息");
            return map;
        }
        try {
            //将用户对象存入session
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            //创建普通邮件对象
            SimpleMailMessage message = new SimpleMailMessage();
            //设置发件人邮箱
            message.setFrom(sendEmail);
            //设置收件人邮箱
            message.setTo(email);
            //设置邮件主题
            message.setSubject("仓库信息管理系统验证码");
            // 生成随机验证码
            Random rd = new Random();
            String valCode = rd.nextInt(9999)+"";
            //设置邮件正文
            message.setText(valCode);
            //发送邮件
            mailSender.send(message);
            //发送成功
            //把验证码存入session中
            session.setAttribute("valCode",valCode);
            map.put("info","发送成功");
            return map;

        } catch (Exception e) {
            System.out.println("发送邮件时发生异常");
            e.printStackTrace();
        }
        map.put("info","发送邮件异常");
        return map;
    }

    @Override
    public HashMap<String, Object> select(User user) {
        HashMap<String, Object> map =  new HashMap<String, Object>();
        //1 设置分页参数
        PageHelper.startPage(user.getPage(),user.getRow());
        //根据用户选中的查询条件判断用户需要查询的
        List<User> list = new ArrayList<>();
        if(user.getConValue().equals("")){
            list = userDao.selectAll();
        }else {
            if(user.getCondition().equals("身份")){
                //设置查询条件
                user.setIdentity(user.getConValue());
                list = userDao.findByUserId(user);
            }else if(user.getCondition().equals("姓名")){
                user.setName(user.getConValue());
                list = userDao.findByUserName(user);
            }else {
                list = userDao.selectAll();
            }
        }
        //3.把查询的数据转换成分页对象
        PageInfo<User> page = new PageInfo<User>(list);

        //获取分页的当前页的集合
        map.put("list",page.getList());
        //总条数
        map.put("total",page.getTotal());
        //总页数
        map.put("totalPage",page.getPages());
        //上一页
        if(page.getPrePage()==0){
            map.put("pre",1);
        }else{
            map.put("pre",page.getPrePage());
        }

        //下一页
        //保持在最后一页
        if(page.getNextPage()==0){
            map.put("next",page.getPages());
        }else{
            map.put("next",page.getNextPage());
        }
        //当前页
        map.put("cur",page.getPageNum());

        return map;
    }

    @Override
    public String updateIdentity(User user) {
        int num = userDao.updateIdentity(user);
        if(num>0){
            return "修改成功";
        }
        return "修改失败";
    }

    @Override
    public String delUser(User user) {
        int num = userDao.delUser(user);
        if(num>0){
            return "删除成功";
        }
        return "删除失败";
    }

    @Override
    public String addUser(User user) {
        User u = userDao.findByTel(user);
        if(u != null){
            return "当前手机号已被注册";
        }else {
            //将用户输入的密码进行加密，并存到数据层
            String pwd = mdFive.encrypt(user.getLogin_pwd(), user.getTel() );
            user.setLogin_pwd(pwd);
            user.setSalt(user.getTel());
            //注册
            int n = userDao.register(user);
            if(n>0){
                return "注册成功";
            }
            return "注册失败";
        }
    }

    @Override
    public User selectByTel(User user) {
        return userDao.findByTel(user);
    }

    @Override
    public String updateUser(User user, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User oldU = (User) session.getAttribute("user");
        user.setOldTel(oldU.getTel());
        User u = userDao.findByTel(user);
        if(u != null && !(user.getTel().equals(user.getOldTel())) ){
            return "当前手机号已被注册";
        }else {
            //将用户输入的密码进行加密，并存到数据层
            String pwd = mdFive.encrypt(user.getLogin_pwd(), user.getTel() );
            user.setLogin_pwd(pwd);
            user.setSalt(user.getTel());
            //
            int n = userDao.updateUser(user);
            if(n>0){
                //将用户对象存入session
                session.setAttribute("user", user);
                return "修改成功";
            }
            return "修改失败";
        }
    }

    @Override
    public String logOut(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("user", null);
        if (session.getAttribute("user") == null){
            return "登出成功";
        }
        return "登出失败";
    }
}
